// Copyright (c) 2023 坚果派
// 公众号：nutpi
// 电话：17752170152
// 官网：https://www.nutpi.net/
// All rights reserved.

import 'package:flutter/material.dart';

class HealthChart extends StatelessWidget {
  final List<double> data;
  final List<String> labels;
  final String title;
  final Color barColor;

  const HealthChart({
    super.key,
    required this.data,
    required this.labels,
    required this.title,
    this.barColor = Colors.green,
  });

  @override
  Widget build(BuildContext context) {
    double maxValue =
        data.reduce((value, element) => value > element ? value : element);

    return Card(
      elevation: 3,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              style: Theme.of(context).textTheme.titleMedium,
            ),
            const SizedBox(height: 16),
            SizedBox(
              height: 200,
              child: Row(
                children: [
                  Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text('${maxValue.toInt()}'),
                      Text('${(maxValue * 0.75).toInt()}'),
                      Text('${(maxValue * 0.5).toInt()}'),
                      Text('${(maxValue * 0.25).toInt()}'),
                      const Text('0'),
                    ],
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: List.generate(data.length, (index) {
                        return _buildBar(
                            context, data[index], labels[index], maxValue);
                      }),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBar(
      BuildContext context, double value, String label, double maxValue) {
    final height = (value / maxValue) * 170;

    return Column(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        Container(
          width: 30,
          height: height,
          decoration: BoxDecoration(
            color: barColor,
            borderRadius: const BorderRadius.vertical(
              top: Radius.circular(4),
            ),
          ),
        ),
        const SizedBox(height: 4),
        Text(label, style: const TextStyle(fontSize: 12)),
      ],
    );
  }
}
